import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Upload, message, Select, Button, Result, Col, Row, Popconfirm, Tooltip } from "antd"
import { InboxOutlined, EllipsisOutlined, SearchOutlined, FileZipOutlined } from '@ant-design/icons';
const { Dragger } = Upload
import { FileUpload, GetFile, DeleteFile, DownloadFiles } from "@/api/File"
import { useState, useEffect, useRef } from 'react'
import { flattenObject } from "@/components/utils/Tools"


export default () => {
    const actionRef = useRef(); //绑定Ref 触发刷新
    const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 初始化选中的行 keys  
    const [filetype, setFiletype] = useState('')
    const [filedata, setFiledata] = useState()
    const [resultlogo, setResultlogo] = useState(false)
    const [tabledata, setTabledata] = useState()
    const [total, setTotal] = useState(0)
    function flattenArray(arr) {
        return arr.map(item => flattenObject(item));
    }
    const GetFileList = async (options) => {
        try {
            console.log('options', options)
            const data = await GetFile(options)
            console.log(data.results)
            setTotal(data.count)
            setTabledata(flattenArray(data.results))
        } catch (err) {
            console.log(err)
        }
    }
    const handleChange = (value: { value: string; label: React.ReactNode }) => {
        // GetFileList()
        console.log(value); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
        setFiletype(value.value)
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys, newSelectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
            console.log('newSelectedRowKeys', newSelectedRowKeys)
            // 在这里可以处理选中行数据 newSelectedRows
        },
        preserveSelectedRowKeys: true, // 翻页时保留选中状态  
    };
    const props = {
        name: 'file',
        // multiple: true,
        maxCount: 1,
        accept: '.xlsx,.xls',
        onChange(info) {
            const { status } = info.file;
            // if (status !== 'uploading') {
            //     console.log(info.file, info.fileList);
            // }
            if (status === 'done') {
                // 文件上传完毕后 计算文件大小  为什么不在 文件上传前执行,因为 info ...
                const maxFileSize = 10
                const { file } = info;
                const fileSizeInMB = file.size / 1024 / 1024; // 将文件大小转换为MB
                // console.log('fileSizeInMB', fileSizeInMB)
                if (fileSizeInMB > maxFileSize) {
                    message.error(`文件大小不能超过${maxFileSize}MB`);
                    // 取消上传
                    // message.error('文件上传已取消');
                    return false; // 阻止上传
                }
                message.success(`${info.file.name} file uploaded successfully.`);

                setFiledata(info)
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };
    // 导入数据处理函数
    const UploadData = async (file) => {
        const formData = new FormData();
        formData.append('file', file);
        if (filetype === '') {
            message.error("文件类型未选择！")
            return
        }
        formData.append('file_type', filetype);
        formData.append('file_name', filedata.file.name);
        try {
            const response = await FileUpload(formData);
            console.log(response)
            // if (response.status === 201) {
            message.success("上传成功！")
            actionRef.current.reload();
            setResultlogo(true)
            //     return
            // }
            // message.info("文件格式出现异常")
        } catch (error) {
            // 处理上传失败的逻辑
            message.error("上传失败！")
        }
    }
    const columns = [
        {
            title: '排序',
            dataIndex: 'index',
            valueType: 'index',
            width: 66,
        },
        {
            title: '文件编码',
            dataIndex: 'id',
            width: 88,
        },
        {
            title: '上传用户',
            dataIndex: 'userusername',
            width: 120,
        },
        {
            title: '文件名',
            dataIndex: 'file_name',
            filters: true,
            onFilter: true,
        },
        {
            title: "文件类型",
            dataIndex: 'file_type',
            valueEnum: {
                '文件类型一': { text: '文件类型一', status: 'Default' },
                '文件类型二': { text: '文件类型二', status: 'Processing' },
                '文件类型三': { text: '文件类型三', status: 'Success' },
            },
        },
        {
            title: '文件上传时间',
            dataIndex: 'uploaded_at',
            valueType: 'dateTime',
            ellipsis: true,
            filters: false,
            search: false,
        },
        {
            title: '文件上传时间',
            dataIndex: 'start_endDateTimeRange',
            valueType: 'dateTimeRange',
            render: () => null,
            width: 0,
            hideInTable: true //控制table显示
            // search: false,
            // filters: false, // 禁用默认的筛选
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (text, record, _, action) => [<Popconfirm
                key="commit"
                title="确定要删除这条记录吗？"
                onConfirm={async () => {
                    try {
                        await DeleteFile(record.id)
                        actionRef.current.reload();
                        message.success('删除成功')
                    } catch (err) {
                        message.error("删除失败")
                    }
                    // console.log(record.id)
                }}
                onCancel={() => {
                    message.info('取消删除');
                }}
                okText="确认"
                cancelText="取消"
            >
                <a>删除</a>
            </Popconfirm>],
        },
    ];
    useEffect(() => {
        GetFileList({})
    }, [])
    return (
        <PageContainer>
            {resultlogo ? <Result
                // style={{height:'220px'}}
                status="success"
                title="上传成功!"
                subTitle="查看上传数据"
                extra={[
                    <Button type="primary" key="console" onClick={() => {
                        // history.push('/user/login');
                        setResultlogo(false)

                    }}>
                        点击返回,继续上传
                    </Button>
                ]}
            /> :
                <>
                    <Row style={{ height: '220px' }}>
                        <Col span={14}>
                        <div style={{ width: 220,marginBottom: '10px' ,fontSize:'18px',fontWeight:'600'}}>选择上传文件:</div>
                            <div style={{ height: '160px', backgroundColor: '#d1d4d6',borderRadius:'8px' }}>
                                <Dragger {...props}  >
                                    <p className="ant-upload-drag-icon">
                                        <InboxOutlined />
                                    </p>
                                    <p className="ant-upload-text">点击上传 或 拖拽文件</p>
                                    <p className="ant-upload-hint">
                                        （您好，当前仅支持上传后缀为<span style={{ color: 'red' }}>.xls .xlsx </span>的Excel文件）
                                    </p>
                                </Dragger>
                            </div>
                        </Col>
                        <Col span={6}>
                           <div style={{ width: 220, marginLeft: '50px',marginBottom: '10px' ,fontSize:'18px',fontWeight:'600'}}>文件类型选择:</div>
                            <Select
                                labelInValue
                                // defaultValue={{ value: 'lucy', label: 'Lucy (101)' }}
                                style={{ width: 220, marginLeft: '50px' }}
                                placeholder="请选择您的文件类型~"
                                onChange={handleChange}
                                options={[
                                    {
                                        value: '文件类型一',
                                        label: '文件类型一',
                                    },
                                    {
                                        value: '文件类型二',
                                        label: '文件类型二',
                                    },
                                    {
                                        value: '文件类型三',
                                        label: '文件类型三',
                                    },
                                ]}
                            />
                        </Col>
                        <Col span={4}>
                        <div style={{ width: 220,marginBottom: '10px' ,fontSize:'18px',fontWeight:'600'}}>上传文件:</div>
                            <Button type="primary" onClick={() => {
                                if (filedata && Object.keys(filedata).length > 0) {
                                    UploadData(filedata.file.originFileObj)
                                    return 0
                                }
                                message.info("暂无数据提供，请上传文件")
                            }}>点击提交文件</Button>
                        </Col>
                    </Row>

                </>
            }
            <ProTable
                actionRef={actionRef}
                rowSelection={rowSelection}
                columns={columns}
                request={(params, sorter, filter) => {
                    // 表单搜索项会从 params 传入，传递给后端接口。
                    // console.log('----------', params, sorter, filter);
                    // 解构出 需要的参数
                    const { current, size, file_name = '', file_neme = '', id = '', file_type, start_endDateTimeRange = ["", ""] ,userusername} = params
                    const uploaded_at__gte = start_endDateTimeRange[0] // 起始时间
                    const uploaded_at__lte = start_endDateTimeRange[1] // 结束时间
                    // console.log('---')
                    GetFileList({ 'page': current, size, file_name, file_neme, id, file_type, uploaded_at__gte, uploaded_at__lte ,'user':userusername})
                    return Promise.resolve({
                        data: tabledata,
                        success: true,
                    });
                }}
                dataSource={tabledata}
                rowKey="id"
                pagination={{
                    total: total,
                    defaultPageSize: 10,
                    showSizeChanger: true, // 显示可调整每页条数功能
                    pageSizeOptions: ['10', '20', '50', '100'], // 指定每页可以显示多少条
                    showQuickJumper: true, // 显示快速跳转到某页功能
                    // onChange: (page) => console.log(page),
                }}
                search={{
                    layout: 'vertical',
                    defaultCollapsed: false,
                }}
                dateFormatter="string"
                toolbar={{
                    title: '文件数据预览',
                    tooltip: '上传的文件预览',
                }}
                toolBarRender={() => [
                    <Tooltip key='tooltip' title="先选择要下载的文件,再点击下载压缩包" >
                        <Button key="danger"  style={{ backgroundColor: 'rgb(8 183 26)', color: '#fff' }} onClick={async () => {
                            if(selectedRowKeys.length === 0){
                                message.info('请选择您要下载的文件')
                                return
                            }
                            const reponse = await DownloadFiles({ 'ids': selectedRowKeys })
                            const blob = new Blob([reponse], { type: 'application/octet-stream' })
                            const url = window.URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = url;
                            const now = new Date();
                            const formattedTime = now.toISOString().slice(0, 10).replace(/-/g, '_') + '_' + now.toTimeString().slice(0, 5).replace(/:/g, '_');
                            link.setAttribute('download', `${formattedTime}_文件压缩包下载.zip`);
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            window.URL.revokeObjectURL(url);
                        }}>
                            点击批量下载文件zip<FileZipOutlined />
                        </Button>
                    </Tooltip>,
                    // <Button key="show">查看日志</Button>,
                    // <Button type="primary" key="primary">
                    //     创建应用
                    // </Button>,
                ]}
            />
        </PageContainer>
    )
}